$(function () {
    //素材类型
    var typeKey = $("input[name='typeKey']").val();
    var options = $("#playType option:selected");　　　　//获取选中项
    var playType = options.val();　　　　　　　　　　　　　　//获取选中项的值

    //添加还是修改页面
    var materialId = $("[name='id']").val();
    //if($("#material-subject-box").length>0&&($("input[name='mouldId']").val()==null || $("input[name='mouldId']").val()=='' || $("input[name='mouldId']").val()<=0)){
        //初始化专业/科目
        $.initSubject({
            element:'material-subject-box',//初始化专业select元素的ID
            context:'material-subject-context',//显示专业/科目名字内容ID
            initSelect: materialId =="" ? true:false,
            removeBtn: materialId =="" ? true:false,
            initData:$('#subjectIds').val(),//初始化显示的专业数据，默认不设置
            removeCallback:function(parentId,subjectIds){//删除回调
                resetSubjectIds()
            },
            confirmCallback:function(parentId,subjectIds){//点击确认回调
                resetSubjectIds()
            },
            successCallback:function () {
                var subjectIds = $("#subjectIds").val();
                initCouMould(subjectIds);
            }
        });
    //}

    //学员,讲师地址生成二维码
    QRCodeInp();

    /**
     * 重置专业ID串
     */
    function resetSubjectIds() {
        var _subjectIds = $.getAllSubjectIds("material-subject-context");
        $("input[name=subjectIds]").val(_subjectIds);
        resetWhenSubjectIllegal();
        if(_subjectIds==null || $.trim(_subjectIds)==''){
            return;
        }
        initCouMould(_subjectIds);
    }

    /**
     * 为选择专业科目时重置与专业科目有关的内容Z
     */
    function resetWhenSubjectIllegal() {
        $('select[name=mouldId]').html('').trigger('chosen:updated');
    }

    /**
     * 初始化隶属模块
     */
    function initCouMould(subjectIds) {
        var params = JSON.stringify({'subjectIds': subjectIds});
        $.ajax({
            url: baseloaction + '/admin/course/mould/selectMouldList',
            data: params,
            dataType: 'json',
            type: 'post',
            contentType: 'application/json;charset=utf-8',
            success: function (response) {
                if (response.success==true) {
                    var element = $('#material-mould-select');
                    // 清空已有选项
                    element.html('<option value="0">请选择模块</option>');
                    var entity = response.entity;
                    entity.forEach(function (v, i) {
                        element.append('<option value="' + v.id + '">' + v.mouldName + '</option>');
                    });
                    var mouldId =$('#mouldId').val();
                    if(mouldId != null){
                        element.val(mouldId);
                    }
                    element.trigger('chosen:updated');
                }
            }
        })
    }

    //如果是文章类型的则初始化编辑器
    if ($('input[name="typeKey"]').val() == 'ARTICLE') {
        //初始化编辑框
        initSNU({
            id:'articleSummary',
            type:1,
            toolsArr:null,
            height:250,
            gs:true,
            video:false
        });
        //初始化编辑框
        initSNU({
            id:'articleContext',
            type:1,
            toolsArr:null,
            height:360,
            gs:true,
            video:false
        });
    }
    //如果是直播类型，则初始化时间控件
    if ($('input[name="typeKey"]').val() == 'LIVE' && $("#playType").val() == 'TT') {
        initLayerDate("#startDate",true);
        initLayerDate("#endDate",true);
    }
    $('body').on('click','#newCreateCCLive',function () {//创建直播
        var liveBilling  = $('input[name="liveBilling"]:radio:checked').val();
        if( liveBilling==''||liveBilling==null||liveBilling==undefined){
            icModale(0, '请选择直播房间类型');
            return;
        }
        newCreateLiveCC(createLiveCallback,liveBilling);
    }).on('click', '#uploadVideo', function () {//上传视频的时间
        var playType = $('select[name="playType"]').val();
        if (playType==null || $.trim(playType) == '') {
            icModale(0, '请先选择视频服务商');
            return false;
        }
        popupWindows();
    }).on('click','#selectVideo',function () {//选择音频、视频
        var typeKey = $("input[name='typeKey']").val();
        selectCommonVideo(typeKey);
    }).on('click',"#selectTeacher",function () {//选择讲师
        var subjectIds = $("input[name='subjectIds']").val();
        if(subjectIds==null || $.trim(subjectIds)==''){
            icModale(0, '请选择专业/科目');
            return;
        }
        selectTeacher('radio',subjectIds,'selectTeacherCallback','1');
    }).on('click', '#deleteTeacher', function () {//删除讲师
        deleteTeacher();
    }).on('click', '#saveCancel', function () {//取消保存
        window.location.href = baseloaction +'/admin/course/material/materialList';
    }).on('change', '#select1, #select2', function () {//专业的改变删除讲师
        deleteTeacher();
    }).on('chosen:showing_dropdown', 'select[name="mouldId"]', function () {//选择模板的时候

    }).on('click',".submitMaterial",function () {//保存素材
        debugger
        var _this = $(this);
        if(typeKey !='ARTICLE' && playType != 'TT'){
            $.ajax({
                url: baseloaction +'/admin/course/material/checkingMaterialCode',
                type:'post',
                dataType:'json',
                async:false,
                data:{
                    'playUrl':$("#playUrl").val(),
                    'typeKey':typeKey
                },
                success:function (result) {
                    if(result.success==false){
                        icModale(2,result.message,3,function () {
                            _save(_this);
                        });
                    }else{
                        _save(_this);
                    }
                },
                error:function (error) {
                    icModale(0, '系统错误，验证素材失败');
                }
            });
        }else{
            _save(_this);
        }
    }).on("ifClicked", "#liveBilling1", function () {
        $("#liveType-hr").show();
        $("#liveType-div").show();
        $("#maxUsers-hr").hide();
        $("#maxUsers-div").hide();
    }).on("ifClicked", "#liveBilling2", function () {
        $("#liveType-div").hide();
        $("#liveType-hr").hide();
        $("#maxUsers-div").show();
        $("#maxUsers-hr").show();
    }).on('click',"#selectAssistant",function () {//选择助教
        var subjectIds = $("input[name='subjectIds']").val();
        if(subjectIds==null || $.trim(subjectIds)==''){
            icModale(0, '请选择专业/科目');
            return;
        }
        selectTeacher('radio',subjectIds,'selectAssistantCallback','1');
    }).on('click', '#deleteAssistant', function () {//删除助教
        deleteAssistant();
    });

    function _save(_this) {
        debugger
        $(".submitMaterial").attr('disabled','disabled');
        var status = _this.data('status');//状态，2保存并发布，1保存返回不发布
        var params = $("#materialFrom").serializeJSON();
        params = JSON.stringify(params);
        $.ajax({
            url:baseloaction +'/admin/course/material/saveMaterial?status='+status,
            type:"post",
            data:params,
            dataType:"json",
            contentType:'application/json;charset=utf-8',
            success:function (result) {
                if(result.success){
                    icModale(1, result.message, 1, function () {
                        window.location.href = baseloaction +'/admin/course/material/materialList';
                    });
                }else {
                    $(".submitMaterial").removeAttr('disabled');
                    icModale(0, result.message);
                }
            },
            error:function (error) {
                $(".submitMaterial").removeAttr('disabled');
                icModale(0, '系统错误，保存素材数据失败');
            }
        });
    }

    /**
     * 删除选中讲师
     */
    function deleteTeacher() {
        $("#teacherName").html("请选择讲师");
        $("#teacherId").val(0);
        $("#deleteTeacher").parent().addClass("hide");
    }

    /**
     * 删除选中助教
     */
    function deleteAssistant() {
        $("#assistantName").html("请选择助教");
        $("#assistantId").val(0);
        $("#deleteAssistant").parent().addClass("hide");
    }

    var index =null;
    /**
     * 上传素材资源时的公共弹窗
     */
    function popupWindows() {
        var type = 0;
        var message = '';
        if(typeKey=='VIDEO'){
            type = 1;//1表示上传视频
            message='请选择要上传的视频文件';
        }else if(typeKey=='AUDIO'|| typeKey=='ARTICLE'){
            type = 2;//2表示上传音频
            message='请选择要上传的视频文件(将自动转成音频文件)';
        }
         index = parent.layer.open({
            type: 2,
            area: ['500px', '100px'],
            content: baseloaction +'/admin/liveToV/create/initVideoUploadPage?type='+type,
            shadeClose: false,
            shade: [0.3, '#000'],
            title: '<strong>'+message+'</strong>'
         });
        setMethods(callbackClose);
    }
    //回调关闭上传素材资源时的公共弹窗
    callbackClose = function (){
        parent.layer.close(index);
        }
    });
var close =null;
function setMethods (to){
    close =to;
}
/**
 * 选择讲师回调
 * @param data
 */
function selectTeacherCallback(data) {
    if (data!=null) {
        $("#deleteTeacher").parent().removeClass('hide');
        $("#teacherName").text(data.teacherName);
        $("#teacherId").val(data.id);
    }
}

/**
 * 选择助教回调
 * @param data
 */
function selectAssistantCallback(data) {
    if (data!=null) {
        $("#deleteAssistant").parent().removeClass('hide');
        $("#assistantName").text(data.teacherName);
        $("#assistantId").val(data.id);
    }
}

//96k 资源上传回调
parent.window.addEventListener('message', function (response) {
    if (!$.isEmptyObject(response)) {
        if ($('input[name="name"]').val() == '') {
            $('input[name="name"]').val(response.data.videoName);
        }
        $('#videoDuration').val(response.data.videoDuration);
        $('input[name="playUrl"]').val(response.data.msg);
        close();
    }
}, false);

/**
 * 创建直播回调
 * @param entity 直播数据对象
 */
function createLiveCallback(entity) {
    $('#roomId').val(entity.room_id);
    $('#teacherCode').val(entity.teacher_code);
    $('#adminCode').val(entity.admin_code);
    $('#studentCode').val(entity.student_code);
    $('#playUrl').val(entity.sign);
    $('#adminUrl').val(entity.adminUrl);
    $('#studentUrl').val(entity.studentUrl);
    $('#teacherUrl').val(entity.teacherUrl);

    $("input:radio[value='"+entity.preEnterTime+"']").iCheck('check');
    $('input[name="preEnterTime"]').val();
    var name = $('#title').val();
    if(name==null||name==''){
        $('#title').val(entity.title);
    }
    var startDate = $('#startDate').val();
    if(startDate==null||startDate==''){
        $('#startDate').val(entity.start_time);
    }
    var endDate = $('#endDate').val();
    if(endDate==null||endDate==''){
        $('#endDate').val(entity.end_time);
    }
    let start = new Date(entity.start_time)
    let end = new Date(entity.end_time)
    $('#videoDuration').val((end-start)/1000);
}

/**
 * 选择回调
 * @param video
 */
function selectVideoCallback(video) {
    $("input[name='playUrl']").val(video.code);
    $("input[name='videoDuration']").val(video.duration);
    var name = $("input[name='name']").val();
    if(name==null || $.trim(name)=='' || typeof name =='undefined'){
        $("input[name='name']").val(video.name);
    }
}

/**
 * 生成二维码
 * @constructor
 */
function QRCodeInp(){
    var studentUrl = $('#studentUrl').val();
    if(studentUrl!=null && studentUrl!=''){
        var qrcode = $('#studentQRCodeInp').qrcode({render: "canvas", height: 140, width: 140, correctLevel: 2, text: studentUrl}).find('canvas').hide();
        $("#studentQRCodeInp").attr('src', qrcode[0].toDataURL());
    }
    var teacherUrl = $('#teacherUrl').val();
    if(teacherUrl!=null && teacherUrl!=''){
        var qrcode = $('#teacherQRCodeInp').qrcode({render: "canvas", height: 140, width: 140, correctLevel: 2, text: teacherUrl}).find('canvas').hide();
        $("#teacherQRCodeInp").attr('src', qrcode[0].toDataURL());
    }
}